package com.alibaba.datax.plugin.writer.kingbaseeswriter.util;

import com.alibaba.datax.common.exception.DataXException;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.plugin.rdbms.writer.Constant;
import com.alibaba.datax.plugin.rdbms.writer.Key;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class KingbaseesUtil {
    private static final Logger LOG = LoggerFactory.getLogger(KingbaseesUtil.class);

    private KingbaseesUtil() {
    }

    public static void dealWriteMode(Configuration originalConfig) throws DataXException {
        List<String> columns = originalConfig.getList(Key.COLUMN, String.class);

        String jdbcUrl = originalConfig.getString(String.format("%s[0].%s",
                Constant.CONN_MARK, Key.JDBC_URL, String.class));

        // 默认为：insert 方式
        String writeMode = originalConfig.getString(Key.WRITE_MODE, "INSERT");

        List<String> valueHolders = new ArrayList<String>(columns.size());
        for (int i = 0; i < columns.size(); i++) {
            valueHolders.add("?");
        }
        String writeDataSqlTemplate = getWriteTemplate(columns, valueHolders);
        LOG.info("----------------->  Write data [\n{}\n], which jdbcUrl like:[{}]", writeDataSqlTemplate, jdbcUrl);
        originalConfig.set(Constant.INSERT_OR_REPLACE_TEMPLATE_MARK, writeDataSqlTemplate);
    }

    public static String getWriteTemplate(List<String> columnHolders, List<String> valueHolders) {
        String writeDataSqlTemplate;
        LOG.info("-------->  人大金仓Insert::Start  <---------");
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO %s (").append(StringUtils.join(columnHolders, ","))
                .append(") VALUES(").append(StringUtils.join(valueHolders, ","))
                .append(")");
//                .append(") ON CONFLICT (ID) DO")
//                .append(" UPDATE SET ");
//        boolean first = true;
//        for (String column : columnHolders) {
//            if (!first) {
//                sb.append(",");
//            } else {
//                first = false;
//            }
//            sb.append(column);
//            sb.append(" = ");
//            sb.append("EXCLUDED." + column);
//        }
        writeDataSqlTemplate = sb.toString();
        LOG.info(writeDataSqlTemplate);
        LOG.info("-------->  人大金仓Insert::End  <---------");
        return writeDataSqlTemplate;
    }
}
